package com.example.big_event.controller;

import com.example.big_event.pojo.Result;
import com.example.big_event.pojo.User;
import com.example.big_event.service.UserService;
import com.example.big_event.utils.JwtUtil;
import com.example.big_event.utils.ThreadLocalUtil;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.print.attribute.standard.PresentationDirection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping ("/hello")
    public Result hello(@RequestBody String requestBody){
        System.out.println("requestBody"+ requestBody);
        System.out.println("hello world");
        return Result.success("hello world");
    }

    @PostMapping("/register")
//    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password){
        public Result register(@RequestParam("username") @Validated String username,
                               @RequestParam("password") @Validated String password){
        //        //判断账户密码长度是否合法
//        if(username!=null && username.length() >= 5 && username.length() <=16 &&
//                password!=null && password.length() >= 5 && password.length() <= 16){

        /*System.out.println(data);
        return Result.success("测试成功");
        System.out.println("用户名："+ username + ",密码："+ password);
        if((username == null) && (password == null)){
            return Result.error("controller获取数据为空");
        }else{
            return Result.success("入参正确，可以继续");
        }*/

            //查询用户
            User user = userService.findByUserName(username);
            if(user == null){
                //注册
                userService.register(username, password);
                return Result.success();
            }else{
                //占用
                return Result.error("用户名已被占用");
            }

//        }else{
//            return Result.error("参数不合法");
//        }
    }

    @PostMapping("/login")
//    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password){
    public Result<String> login(@RequestParam("username") @Validated String username,
                                @RequestParam("password") @Validated String password){
        System.out.println("账户名:"+username+" ,密码:"+password);
//        根据用户名查询用户
        User loginUser = userService.findByUserName(username);
        //判断用户是否存在
        if(loginUser == null){
            return Result.error("用户名错误");
        }

        //根据密码来匹配是否正确
        if(password.equals(loginUser.getPassword())){
            //生成token
            Map<String, Object> claim = new HashMap<>();
            claim.put("id",loginUser.getId());
            claim.put("username", loginUser.getUsername());
            String token = JwtUtil.genToken(claim);
//            return Result.success("登录成功,生成token");
            System.out.println("登录成功");
            //将数据存储到redis中
            stringRedisTemplate.opsForValue().set(token, token,1, TimeUnit.HOURS);
            return Result.success(token);
        }

        return Result.error("密码错误");
    }

    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/){
        //根据用户名查询用户
       /*Map<String, Object> map = JwtUtil.parseToken(token);
        String username = (String) map.get("username");*/

        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated({User.Update.class}) User user){
        System.out.println(user);
        userService.update(user);

        return Result.success();
    }

    @PutMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);

        return Result.success();
    }

    @PutMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params,  @RequestHeader("Authorization") String token){
        //校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数");
        }
//        System.out.println("oldPwd" + oldPwd + "newPwd" + newPwd + "rePwd" + rePwd);
        //校验原密码是否正确
        Map<String ,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userService.findByUserName(username);
//        System.out.println("loginUser.getPassword()" + loginUser.getPassword());
        if(!loginUser.getPassword().equals(oldPwd)){
            return Result.error("原密码错误");
        }

        //新密码和确认密码相同
        if(!rePwd.equals(newPwd)){
            return Result.error("两次密码输入不同");
        }
        //调用service完成密码更新
        userService.updatePwd(newPwd);

        //删除redis中token
        stringRedisTemplate.opsForValue().getOperations().delete(token);
        return Result.success();
    }

    //注册页面的代码1          ----->可以用Spring Validation对注册接口的参数进行合法性校验
    //public Result register(String username, String password){
    //        //判断账户密码长度是否合法
    //        if(username!=null && username.length() >= 5 && username.length() <=16 &&
    //                password!=null && password.length() >= 5 && password.length() <= 16){
    //            //查询用户
    //            User user = userService.findByUserName(username);
    //            if(user == null){
    //                //注册
    //                userService.register(username, password);
    //                return Result.success();
    //            }else{
    //                //占用
    //                return Result.error("用户名已被占用");
    //            }
    //        }else{
    //            return Result.error("参数不合法");
    //        }
}
